package com.sinoglobal.ningxia.activity.mico;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.MyCollectionActivity;
import com.sinoglobal.ningxia.adapter.ProgramInfoFragmentAdapter;
import com.sinoglobal.ningxia.beans.MicProgramBean;
import com.sinoglobal.ningxia.beans.ProgramaListBean;
import com.sinoglobal.ningxia.beans.RootVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.frame.ShareAbstractActivity;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.widget.MyProgress;

import net.tsz.afinal.FinalBitmap;

/**
 * @author qiwx
 * @createdate 2014-6-24 下午1:34:35
 * @Description:栏目详情页
 */
@SuppressLint("NewApi")
public class ProgramInfoActivity extends ShareAbstractActivity implements
        OnClickListener, OnPageChangeListener {
    private static final int TAB_HISTORY = 0;// 剧集
    private static final int TAB_COMMENT = 1;// 评论
    ViewPager viewPager;
    RadioButton historyRaidoBtn;// 剧集
    RadioButton commentRadioBtn;// 评论
    ProgramInfoFragmentAdapter adapter;// 剧集与评论适配器
    Context mContext;
    PopupWindow pow;// 功能菜单
    private LinearLayout popwindowView;
    private TextView topView;// 设置一个像素，为了popupwindow做参照
    private LinearLayout share;// 分享功能
    private LinearLayout collect;// 收藏功能
    private ImageView collectImg;// 收藏Imgview
    private TextView collectState;// 收藏状态
    private byte collectNo = 1;// 未收藏
    private byte collected = 2;// 已收藏
    private ItktAsyncTaskWithDialog<Void, Void, RootVo> mTask;// 加载数据
    private ProgramaListBean.ListBean.LanmuBean bean;
    private String thumbUrl;// 节目缩略图地址
    private String programId;// 栏目id
    FinalBitmap fb;
    private TextView isHot;// 是否热门
    private TextView isStatus;// 播放状态
    private TextView compere;// 主持人
    private TextView startTime;// 播出时间
    private TextView introduce;// 栏目介绍
    private ImageView thumbImg;// 栏目缩略图
    private TextView programName;// 栏目名称
    private ItktAsyncTaskWithDialog<String, MyProgress, MicProgramBean> task;
    private int cllectTag;//是否收藏
    private String isFromCollection = "";// 用于判断是否从我的收藏界面跳转过来
    private Bitmap defaultPic;
    private static RadioButton imgDropDown;// 下拉列表,展示节目介绍
    private static ScrollView mScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.program_info_activity);
        openChenJInShi();//开启沉浸式
        mContext = this;
        init();
        getParameters();

    }

    /**
     * @author qiwx
     * @createdate 2014-10-13 上午10:23:15
     * @description
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTask != null
                && mTask.getStatus() == AsyncTask.Status.RUNNING) {
            mTask.cancel(true);// 如果Task还在运行，则先取消它
            mTask = null;
        }
        if (task != null
                && task.getStatus() == AsyncTask.Status.RUNNING) {
            task.cancel(true);// 如果Task还在运行，则先取消它
            task = null;
        }

    }

    private void init() {
        fb = FinalBitmap.create(this);
        defaultPic = BitmapFactory.decodeResource(getResources(),
                R.drawable.default43);
        fb = FinalBitmap.create(this);
        imgDropDown = (RadioButton) findViewById(R.id.btn_drop_down);
        imgDropDown.setOnClickListener(this);
        /*imgDropDown.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(imgDropDown.isc&&){
					mScrollView.setVisibility(View.GONE);
				}else{
					mScrollView.setVisibility(View.VISIBLE);
				}
			}
		});*/
        mScrollView = (ScrollView) findViewById(R.id.scro_introduce);
        isFromCollection = getIntent().getStringExtra(
                FlyApplication.isFromCollection);
        isHot = (TextView) findViewById(R.id.isHot);
        isStatus = (TextView) findViewById(R.id.isStatus);
        topView = (TextView) findViewById(R.id.topview);
        programName = (TextView) findViewById(R.id.programName);
        compere = (TextView) findViewById(R.id.compere);
        startTime = (TextView) findViewById(R.id.startTime);
        introduce = (TextView) findViewById(R.id.introduce);
        thumbImg = (ImageView) findViewById(R.id.thumb);
        templateButtonRight.setVisibility(View.GONE);
        microButtonRight.setVisibility(View.VISIBLE);
        microButtonRight.setImageResource(R.drawable.top_actionbar_bg);
        microButtonRight.setOnClickListener(this);
        historyRaidoBtn = (RadioButton) findViewById(R.id.programHistory);
        commentRadioBtn = (RadioButton) findViewById(R.id.programComment);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        historyRaidoBtn.setOnClickListener(this);
        commentRadioBtn.setOnClickListener(this);
        viewPager.setOnPageChangeListener(this);
        pow = new PopupWindow(ProgramInfoActivity.this);
        popwindowView = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.program_fuction_menu, null);
        share = (LinearLayout) popwindowView.findViewById(R.id.share);
        share.setOnClickListener(this);
        collect = (LinearLayout) popwindowView.findViewById(R.id.collect);
        collect.setOnClickListener(this);
        collectImg = (ImageView) popwindowView.findViewById(R.id.collect_img);
        collectState = (TextView) popwindowView
                .findViewById(R.id.tvCollectState);
        pow.setContentView(popwindowView);
        setUpPop(pow);
        templateButtonLeft.setOnClickListener(this);
    }


    // 获取上级传递过来的参数

    /**
     * @throws Exception
     * @author qiwx
     * @createdate 2014-7-14 下午7:15:32
     * @Description:
     * @type
     */

    private void getParameters() {
        Intent get = getIntent();
        bean = (ProgramaListBean.ListBean.LanmuBean) get.getSerializableExtra(ProgramaListBean.class
                .getName());
        programId = bean.getLanmuid();
        getMicInfo(bean.getLanmuid());
    }

    public static void hideRb() {
        if (mScrollView.getVisibility() == View.VISIBLE) {
            mScrollView.setVisibility(View.GONE);
            imgDropDown.setChecked(true);
        }
    }

    // 更新栏目信息
    private void updateMicInfo(MicProgramBean bean) {
        if (!(bean.getCode() == Code.CODE_SUCCESS))
            return;
        titleView.setText(bean.getLanmuname());
        thumbUrl = ConnectionUtil.localUrl + bean.getLanmuimage();
        adapter = new ProgramInfoFragmentAdapter(getSupportFragmentManager(),
                mContext, programId);
        viewPager.setAdapter(adapter);
        if (bean.getHot() == 1) {
            isHot.setText(R.string.isHot);
            isHot.setVisibility(View.VISIBLE);
        } else {
            isHot.setVisibility(View.GONE);
        }
        if (bean.getBochu() == 1) {
            isStatus.setText(R.string.isStatus);
            isStatus.setVisibility(View.VISIBLE);
        } else {
            isStatus.setVisibility(View.GONE);
        }
        cllectTag = bean.getShoucang();
        if (bean.getShoucang() == collectNo) {
            collectImg.setImageDrawable(mContext.getResources().getDrawable(
                    R.drawable.collect));
            collectState.setText(mContext.getResources().getString(
                    R.string.collect));
            collectState.setTextColor(mContext.getResources().getColor(
                    R.color.gray));

        } else if (bean.getShoucang() == collected) {
            collectImg.setImageDrawable(mContext.getResources().getDrawable(
                    R.drawable.collected));
            collectState.setText(mContext.getResources().getString(
                    R.string.collected));
            collectState.setTextColor(mContext.getResources().getColor(
                    R.color.red));
        }
        compere.setText(bean.getHost());
        startTime.requestFocus();// 获取焦点
        startTime.setText(bean.getTime_str());
        introduce.setText(bean.getContent());
        programName.setText(bean.getLanmuname());

        int width = FlyApplication.widthPixels / 2
                - EquipmentUtil.px2dip(getApplicationContext(), 10);
        int height = 45 * width / 67;
        thumbImg.setLayoutParams(new LinearLayout.LayoutParams(width, height));
        fb.display(thumbImg, thumbUrl, width, height, defaultPic, defaultPic);
    }

    // 获取栏目信息
    private void getMicInfo(String id) {
        task = new ItktAsyncTaskWithDialog<String, MyProgress, MicProgramBean>() {

            @Override
            public void exception() {

            }

            @Override
            public MicProgramBean before(String... params) throws Exception {
                return RemoteImpl.getInstance().getLanmuInfo(params[0],
                        params[1]);

            }

            @Override
            public void after(MicProgramBean result) {
                if (null == result) {
                    return;
                }
                updateMicInfo(result);
            }
        };
        task.execute(programId, FlyApplication.userId);
    }

    @Override
    public void onBackPressed() {
        if ("1".equals(isFromCollection)) {
            Intent intent = new Intent(ProgramInfoActivity.this,
                    MyCollectionActivity.class);
            ProgramInfoActivity.this.startActivity(intent);
            ProgramInfoActivity.this.finish();
        } else {
            ProgramInfoActivity.this.finish();
        }
        super.onBackPressed();
    }

    private void setUpPop(PopupWindow pop) {

        int popWidth = FlyApplication.widthPixels / 4
                + EquipmentUtil.px2dip(getApplicationContext(), 50);
        pop.setWidth(popWidth);
        pop.setHeight(4 * popWidth / 5);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(+R.color.half_transparent);
        // 需要设置一下此参数，点击外边可消失
        pop.setBackgroundDrawable(dw);
        // 设置点击窗口外边窗口消失
        pop.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        pop.setFocusable(true);
        pop.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mico_but_right:
                // pow.showAsDropDown(templateButtonRight);
                pow.showAsDropDown(topView);
                break;
            case R.id.title_but_left:
                if ("1".equals(isFromCollection)) {
                    Intent intent = new Intent(ProgramInfoActivity.this,
                            MyCollectionActivity.class);
                    ProgramInfoActivity.this.startActivity(intent);
                    ProgramInfoActivity.this.finish();
                } else {
                    ProgramInfoActivity.this.finish();
                }
                break;
            case R.id.programHistory://剧集历史
                viewPager.setCurrentItem(0);
                break;
            case R.id.programComment://评论列表
                viewPager.setCurrentItem(1);
                break;
            case R.id.share:// 分享
                String share;
                try {
                    share = bean.getFenxiang();
                    if (TextUtil.stringIsNull(share))
                        share = getString(R.string.share);
                } catch (Exception e) {
                    e.printStackTrace();
                    share = getString(R.string.share);
                }
                showPopwindow(true, share, null, ConnectionUtil.MicDoorAdress);
                if (pow != null && pow.isShowing())
                    pow.dismiss();
                break;
            case R.id.collect:// 收藏
                if (isLoginIntentLoginActivity())
                    loadData();
                break;
            case R.id.btn_drop_down:

                if (mScrollView.getVisibility() == View.VISIBLE) {
                    mScrollView.setVisibility(View.GONE);
                    imgDropDown.setChecked(true);
                } else {
                    mScrollView.setVisibility(View.VISIBLE);
                    imgDropDown.setChecked(false);
                }
                break;
        }

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageSelected(int id) {
        switch (id) {
            case TAB_HISTORY:
                historyRaidoBtn.setChecked(true);
                historyRaidoBtn
                        .setTextColor(getResources().getColor(R.color.white));
                commentRadioBtn
                        .setTextColor(getResources().getColor(R.color.black));
                break;
            case TAB_COMMENT:
                commentRadioBtn.setChecked(true);
                commentRadioBtn
                        .setTextColor(getResources().getColor(R.color.white));
                historyRaidoBtn
                        .setTextColor(getResources().getColor(R.color.black));
                break;
        }
    }

    /**
     * @throws Exception
     * @author qiwx
     * @createdate 2014-7-24 上午10:36:03
     * @Description:
     * @type
     * @parameters
     */
    @Override
    protected void onStop() {
        super.onStop();

    }

    /**
     * @throws Exception
     * @author qiwx
     * @createdate 2014-7-5 上午10:14:58
     * @Description:请求数据
     * @type
     */
    private void loadData() {
        mTask = new ItktAsyncTaskWithDialog<Void, Void, RootVo>(getString(R.string.wait_a_minute), true,
                true) {

            @Override
            public RootVo before(Void... params) throws Exception {
                try {
                    if (cllectTag == collected) {
                        bean.setShoucang((byte) collectNo);
                        return RemoteImpl.getInstance().add2DelCollect(
                                FlyApplication.userId, MContants.TYPE_CHANNEL,
                                MContants.ACTION_DEL, bean.getLanmuid());
                    } else {
                        bean.setShoucang((byte) collected);
                        return RemoteImpl.getInstance().add2DelCollect(
                                FlyApplication.userId, MContants.TYPE_CHANNEL,
                                MContants.ACTION_ADD, bean.getLanmuid());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }

            }

            @Override
            public void after(RootVo result) {
                if (result == null)
                    return;
                if (Code.CODE_SUCCESS == result.getCode()) {
                    setData(result);
                }
            }

            @Override
            public void exception() {
            }
        };
        mTask.execute();
    }

    private void setData(RootVo vo) {
        if (null != vo) {
            // showShortToastMessage(vo.getMessage());
            cllectTag = bean.getShoucang();
            if (bean.getShoucang() == collected) {
                collectImg.setImageDrawable(mContext.getResources()
                        .getDrawable(R.drawable.collected));
                collectState.setText(mContext.getResources().getString(
                        R.string.collected));
                collectState.setTextColor(mContext.getResources().getColor(
                        R.color.red));
                showShortToastMessage(mContext.getResources().getString(
                        R.string.collectSuccess));
            } else {
                collectImg.setImageDrawable(mContext.getResources()
                        .getDrawable(R.drawable.collect));
                collectState.setText(mContext.getResources().getString(
                        R.string.collect));
                collectState.setTextColor(mContext.getResources().getColor(
                        R.color.gray));
                showShortToastMessage(mContext.getResources().getString(
                        R.string.collectCancel));
            }

        }

    }

}
